package com.token;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JWTFilter extends BasicHttpAuthenticationFilter {

/**
     * 第二步
     * 是否能进下一步处理
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return true可以访问action了，false则执行onAccessDenied
     */

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            //得到客户端传过来的令牌
            String token = ((HttpServletRequest) request).getHeader("token");
            //封装
            Subject subject = getSubject(request, response);
            if(token!=null && token.length()>0){
                JWTToken jwtToken = new JWTToken(token);
                //登录:实际是调用LoginRealm里面doGetAuthenticationInfo
                subject.login(jwtToken);
            }
            //判断是否有权限
            String url = ((HttpServletRequest) request).getRequestURI();
            String regex = "^(/\\w*)(/\\w*)?";
            String api = null;
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(url);
            if(matcher.find()) {
                api = matcher.group(1);
            }
           subject.checkPermission(api);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse r = (HttpServletResponse) response;
        r.setStatus(403);
        return false;
    }

/**
     * 用于跨域   第一步
     *
     * @param request
     * @param response
     * @return true可以进下一步isAccessAllowed，如果false则被拦截不能通过
     * @throws Exception
     */

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "token");

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request,response);

    }
}
